/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.core.sql.utils;

import com.wallellen.core.sql.query.DBRule;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.persister.entity.AbstractEntityPersister;

import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/9/15.
 */
public abstract class HibernateSQLTools<E> {
    private AbstractEntityPersister classMetadata;

    protected abstract Class<?> getTypeClass();

    protected abstract SessionFactory getSessionFactory();

    public static String getValusSqlStr(Map<String, Object> keyValses) {
        boolean isFirst = true;
        StringBuffer returnStr = new StringBuffer();
        for (Map.Entry node : keyValses.entrySet()) {
            if (isFirst)
                isFirst = false;
            else {
                returnStr.append(",");
            }
            returnStr.append((String) node.getKey());
            returnStr.append(" = ");
            returnStr.append("'");
            returnStr.append(node.getValue());
            returnStr.append("'");
        }
        return returnStr.toString();
    }

    public void deleteSqlFromFunction(Session session, List<DBRule> rules) {
        this.classMetadata = ((AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass()));
        String whereStr;
        if ((rules == null) || (rules.size() <= 0))
            whereStr = "";
        else {
            whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
        }
        SQLQuery sqlquery = session.createSQLQuery("DELETE FROM " + this.classMetadata.getTableName() + whereStr);

        sqlquery.executeUpdate();
    }

    public List<E> selectSqlFromFunction(Session session, List<DBRule> rules) {
        this.classMetadata = ((AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass()));
        String whereStr;
        if ((rules == null) || (rules.size() <= 0))
            whereStr = "";
        else {
            whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
        }
        Query sqlquery = session.createQuery("FROM " + getTypeClass().getName() + whereStr);

        List list = sqlquery.list();
        return list;
    }

    public void updataSqlFromFunction(Session session, Map<String, Object> values, List<DBRule> rules) {
        this.classMetadata = ((AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass().getClass()));

        if ((values == null) || (values.size() <= 0))
            return;
        String whereStr;
        if ((rules == null) || (rules.size() <= 0))
            whereStr = "";
        else {
            whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
        }
        SQLQuery sqlquery = session.createSQLQuery("UPDATE " + this.classMetadata.getTableName() + " SET " + getValusSqlStr(values) + whereStr);

        sqlquery.executeUpdate();
    }

    public int countSqlFromFunction(Session session, List<DBRule> rules) {
        this.classMetadata = ((AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass()));
        String whereStr;
        if ((rules == null) || (rules.size() <= 0))
            whereStr = "";
        else {
            whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
        }
        SQLQuery sqlquery = session.createSQLQuery("select count(*) num FROM " + this.classMetadata.getTableName() + whereStr);

        List list = sqlquery.list();
        return Integer.valueOf(list.get(0).toString()).intValue();
    }
}
